package com.boc.ewr.outsrc.controller;

import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.boc.ewr.business.entity.ProPrbsdList;
import com.boc.ewr.util.MsgCategoryEnum;
import com.boc.ewr.util.ToUserUtil;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import com.boc.ewr.outsrc.entity.OutsrcExpStlmtBatch;
import com.boc.ewr.outsrc.service.IOutsrcExpStlmtBatchService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 费用结算（批量）
 * @Author: jeecg-boot
 * @Date: 2023-06-19
 * @Version: V1.0
 */
@Api(tags = "费用结算（批量）")
@RestController
@RequestMapping("/outsrc/outsrcExpStlmtBatch")
@Slf4j
public class OutsrcExpStlmtBatchController extends JeecgController<OutsrcExpStlmtBatch, IOutsrcExpStlmtBatchService> {
    @Autowired
    private IOutsrcExpStlmtBatchService outsrcExpStlmtBatchService;

    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 定义任务线程池
     */
    private static ExecutorService threadPool = new ThreadPoolExecutor(
            1,
            5,
            1000,
            TimeUnit.MILLISECONDS,
            new SynchronousQueue<Runnable>(),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy()
    );

    /**
     * 分页列表查询
     *
     * @param outsrcExpStlmtBatch
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "费用结算（批量）-分页列表查询")
    @ApiOperation(value = "费用结算（批量）-分页列表查询", notes = "费用结算（批量）-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<OutsrcExpStlmtBatch>> queryPageList(OutsrcExpStlmtBatch outsrcExpStlmtBatch,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<OutsrcExpStlmtBatch> queryWrapper = QueryGenerator.initQueryWrapper(outsrcExpStlmtBatch, req.getParameterMap());
        Page<OutsrcExpStlmtBatch> page = new Page<OutsrcExpStlmtBatch>(pageNo, pageSize);
        IPage<OutsrcExpStlmtBatch> pageList = outsrcExpStlmtBatchService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 生成费用
     *
     * @param outsrcExpStlmtBatch
     * @param req
     * @return
     */
    //@AutoLog(value = "费用结算（批量）-生成费用")
    @ApiOperation(value = "费用结算（批量）-生成费用", notes = "费用结算（批量）-生成费用")
    @GetMapping(value = "/calCost")
    public Result<List<OutsrcExpStlmtBatch>> calCost(OutsrcExpStlmtBatch outsrcExpStlmtBatch,
                                                     HttpServletRequest req) {
        QueryWrapper<OutsrcExpStlmtBatch> queryWrapper = QueryGenerator.initQueryWrapper(outsrcExpStlmtBatch, req.getParameterMap());
        List<OutsrcExpStlmtBatch> list = outsrcExpStlmtBatchService.list(queryWrapper);

        String username = this.getLoginUser().getUsername();
        Callable<String> call = () -> {
            log.info("费用结算 生成费用 异步任务开始 {}", Thread.currentThread().getName());

            List<OutsrcExpStlmtBatch> outsrcExpStlmtBatches = outsrcExpStlmtBatchService.calCost(list);
            outsrcExpStlmtBatchService.updateBatchById(outsrcExpStlmtBatches);
            log.info("费用结算 生成费用 异步任务结束 {}", Thread.currentThread().getName());
            this.sendMsg(username);
            return "费用结算 生成费用 成功！！！！";
        };
        threadPool.submit(call);

        return Result.OK("正在进行费用计算，请稍等...");
    }


    /**
     * 添加
     *
     * @param outsrcExpStlmtBatch
     * @return
     */
    @AutoLog(value = "费用结算（批量）-添加")
    @ApiOperation(value = "费用结算（批量）-添加", notes = "费用结算（批量）-添加")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_batch:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody OutsrcExpStlmtBatch outsrcExpStlmtBatch) {
        outsrcExpStlmtBatchService.save(outsrcExpStlmtBatch);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param outsrcExpStlmtBatch
     * @return
     */
    @AutoLog(value = "费用结算（批量）-编辑")
    @ApiOperation(value = "费用结算（批量）-编辑", notes = "费用结算（批量）-编辑")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_batch:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody OutsrcExpStlmtBatch outsrcExpStlmtBatch) {
        outsrcExpStlmtBatchService.updateById(outsrcExpStlmtBatch);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "费用结算（批量）-通过id删除")
    @ApiOperation(value = "费用结算（批量）-通过id删除", notes = "费用结算（批量）-通过id删除")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_batch:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        outsrcExpStlmtBatchService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "费用结算（批量）-批量删除")
    @ApiOperation(value = "费用结算（批量）-批量删除", notes = "费用结算（批量）-批量删除")
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_batch:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.outsrcExpStlmtBatchService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "费用结算（批量）-通过id查询")
    @ApiOperation(value = "费用结算（批量）-通过id查询", notes = "费用结算（批量）-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<OutsrcExpStlmtBatch> queryById(@RequestParam(name = "id", required = true) String id) {
        OutsrcExpStlmtBatch outsrcExpStlmtBatch = outsrcExpStlmtBatchService.getById(id);
        if (outsrcExpStlmtBatch == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(outsrcExpStlmtBatch);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param outsrcExpStlmtBatch
     */
    //@RequiresPermissions("com.boc.ewr:outsrc_exp_stlmt_batch:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, OutsrcExpStlmtBatch outsrcExpStlmtBatch) {
        return super.exportXls(request, outsrcExpStlmtBatch, OutsrcExpStlmtBatch.class, "费用结算（批量）");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("outsrc_exp_stlmt_batch:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, OutsrcExpStlmtBatch.class);
    }

    // 获取登录用户信息
    private LoginUser getLoginUser() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        return sysUser;
    }

    private void sendMsg(String username) {
        MessageDTO messageDTO = new MessageDTO(
                "system",
                username,
                "费用结算-费用计算成功！",
                "费用结算-费用计算成功，请及时查看并导出（下载）数据",
                MsgCategoryEnum.NOTICE.getIndex()
        );
        sysBaseAPI.sendSysAnnouncement(messageDTO);
    }

}
